# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Drop Path block."""
import numpy as np

from mindspore import dtype
from mindspore import nn
from mindspore import ops
from mindspore import Tensor

__all__ = ['FixedprobDropPath1D', 'Identity']


class FixedprobDropPath(nn.Cell):
    """
    Drop path per sample using a fixed probability.
    Use keep_prob param as the probability for keeping network units.

    Args:
        keep_prob (int): Network unit keeping probability.
        ndim (int): Number of dropout features' dimension.

    Inputs:
        Tensor of shape (B, N, C).

    Outputs:
        A path-dropped tensor.
    """

    def __init__(self, keep_prob, ndim):
        super().__init__()
        self.drop = nn.Dropout(keep_prob=keep_prob)
        shape = (1,) + (1,) * (ndim + 1)
        self.ndim = ndim
        self.mask = Tensor(np.ones(shape), dtype=dtype.float32)

    def construct(self, x):
        if not self.training:
            return x
        mask = ops.Tile()(self.mask, (x.shape[0],) + (1,) * (self.ndim + 1))
        out = self.drop(mask)
        out = out * x
        return out


class FixedprobDropPath1D(FixedprobDropPath):
    """FixedprobDropPath module for 1D features."""
    def __init__(self, keep_prob):
        super().__init__(keep_prob=keep_prob, ndim=1)


class Identity(nn.Cell):
    """Return original model."""

    def construct(self, x):
        return x
